<template>
  <el-dialog
    ref="wkDialog"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    width="700px"
    @close="handleCancel">
    <span slot="title" class="el-dialog__title">
      {{ title }}
      <i
        v-if="helpObj"
        class="wk wk-icon-fill-help wk-help-tips"
        :data-type="helpObj.dataType"
        :data-id="helpObj.dataId" />
    </span>
    <div class="form-add-dialog-body">
      <wk-form
        ref="formAddForm"
        :model="editForm"
        :rules="rules"
        :field-from="editForm"
        :field-list="fields"
        :validate-on-rule-change="false"
        class="is-dialog"
        label-position="top"
        @change="wkFormChange"
      >
        <template slot-scope="scope">
          <!-- <slot :data="scope.data" /> -->
          <v-distpicker
            v-if="scope.data && scope.data.formType == 'city'"
            :province="editForm[scope.data.field].province"
            :city="editForm[scope.data.field].city"
            :disabled="scope.data.disabled"
            hide-area
            @province="selectProvince($event, scope.data)"
            @city="selectCity($event, scope.data)" />
        </template>
      </wk-form>
      <create-sections v-if="title === '办理离职' || title === '人员调动' || title === '职位层级调整'" :title="getTitle()">
        <el-button icon="el-icon-plus" @click="addMaterialClick" circle></el-button>
        <el-button icon="el-icon-delete" :disabled="multiple" @click="deleteMaterialClick" circle></el-button>
        <el-table
          :data="materialList"
          @selection-change="handleSelectionChange"
          style="width: 100%; margin-top: 10px">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="type" label="类型" :formatter="typeFormat"/>
          <el-table-column prop="fileName" label="文件名称" />
        </el-table>
      </create-sections>

      <!--  材料上传  -->
      <el-dialog title="材料上传"
                 :visible.sync="materialOpen"
                 width="25%"
                 v-if="materialOpen"
                 append-to-body
                 v-loading="materialLoading"
      >
        <el-form ref="form" :model="empMaterial" label-width="20px" label-position="top">
          <el-form-item label="类型" prop="subType" style="width: 120%">
            <el-select
              v-model="empMaterial.subType">
              <el-option
                v-for="(item, index) in materialTypeList"
                :key="item.typeId"
                :label="item.name"
                :value="item.typeId" />
            </el-select>
          </el-form-item>
          <el-form-item label="材料" prop="type">
            <div
              class="files-box-detail">
              <flexbox
                :gutter="0"
                wrap="wrap">
                <flexbox-item
                  v-if="detailList.length <= 0"
                  :span="10/1"
                  class="detail-cell">
                  <div class="cell-upload-box">
                    <el-upload
                      :show-file-list="false"
                      :http-request="fileUpload"
                      action="http"
                      drag
                      multiple>
                      <i class="wk wk-icon-upload upload-icon"/>
                      <div class="upload-name">点击或拖拽上传</div>
                    </el-upload>
                  </div>
                </flexbox-item>
                <flexbox-item
                  v-if="detailList.length > 0"
                  v-for="(item, index) in detailList"
                  :key="index"
                  :span="10/1"
                  class="detail-cell">
                  <div class="detail-cell-box">
                    <div class="detail-cell-body">
                  <span>
                    <img
                      v-if="isShowImage(item.file.name)"
                      :key="item.file.url"
                      v-src="item.file.url">
                    <img
                      v-if="!isShowImage(item.file.name)"
                      :key="item.file.url"
                      v-src="getFileTypeIcon(item.file.url)">
                  </span>

                      <div class="body-handle">
                        <div class="handle-items">
                      <span
                        class="handle-item"
                        @click="previewFile(item, index)">
                        <i class="wk wk-icon-eye-solid" />
                      </span>
                        </div>
                      </div>
                    </div>
                    <flexbox class="detail-cell-footer">
                      <div
                        v-if="editDetailIndex!=index"
                        class="footer-name">{{ item.file.name }}</div>
                      <el-input
                        v-if="editDetailIndex==index"
                        ref="editInput"
                        v-model="editInputContent"
                        autofocus
                        placeholder="请输入内容"
                        @blur="editInputBlur" />
                      <i
                        class="wk wk-edit footer-item"
                        @click="handleDetailItemClick('edit',item, index)" />
                      <i
                        class="wk wk-s-delete footer-item"
                        @click="handleDetailItemClick('delete',item, index)" />
                    </flexbox>
                  </div>
                </flexbox-item>
              </flexbox>
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="materialOpen = false">取 消</el-button>
        <el-button type="primary" @click="materialSubmit">确 定</el-button>
      </span>
      </el-dialog>
      <slot />
    </div>
    <span
      slot="footer"
      class="dialog-footer">
      <el-button
        v-debounce="handleConfirm"
        type="primary">保存</el-button>
      <el-button @click.native="handleCancel">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import WkForm from '@/components/NewCom/WkForm'
import VDistpicker from '@/components/VDistpicker'

import {getFileIconWithSuffix, objDeepCopy} from '@/utils'
import ElDialogLoadingMixin from '@/mixins/ElDialogLoading'
import CreateSections from "@/components/CreateSections.vue";
import {employeeModel} from "@/views/hrm/employee/model/employee";
import {adminFileQueryByIdAPI, adminFileRenameFileAPI, adminFileUploadAPI} from "@/api/admin/file";

export default {

  // 组织操作
  name: 'FormAddDialog',
  components: {
    CreateSections,
    WkForm,
    VDistpicker
  },
  mixins: [ElDialogLoadingMixin],
  props: {
    title: String,
    form: Object,
    rules: Object,
    fields: Array,
    helpObj: Object,
    visible: {
      type: Boolean,
      required: true,
      default: false
    }
  },
  data() {
    return {
      /** 详情list */
      detailList: [],
      editDetailItem: {},
      editInputContent: '',
      editDetailIndex: -1,
      empMaterial: {},
      materialTypeList: [],
      materialOpen: false,
      materialLoading: false,
      // 选中数组
      ids: [],
      multiple: true,
      materialList: [],
      loading: false,
      editForm: {}
    }
  },
  computed: {
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            if (this.$refs.formAddForm) {
              this.editForm = objDeepCopy(this.form || {})
              this.$refs.formAddForm.$children[0].clearValidate()
            }
          })
          this.materialList = [];
        }
      },
      immediate: true
    },
    form: {
      handler(val) {
        this.editForm = objDeepCopy(this.form || {})
      },
      immediate: true
    },
    title: {
      handler(val) {
        this.getFileTypeList()
      },
    }
  },
  mounted() {
  },
  methods: {
    getTitle() {
      if (this.title === '办理离职') {
        return '离职材料';
      } else if (this.title === '人员调动') {
        return '异动材料';
      } else if (this.title === '职位层级调整') {
        return '其他材料';
      }else {
        return '审核材料';
      }
    },
    typeFormat(row) {
      let typeData = employeeModel.fileType.find(item => row.subType == item.typeId)
      return typeData.name;
    },
    getFileTypeList() {
      this.materialTypeList = employeeModel.fileType.filter(item => {
        if (this.title === '办理离职'){
          return item.typeId > 30 && item.typeId < 40;
        }else if (this.title === '人员调动') {
          return item.typeId > 40 && item.typeId < 50;
        }else if (this.title === '职位层级调整') {
          return item.typeId > 50;
        }
      })
    },
    handleDetailItemClick(type, item, index) {
      if (type == 'edit') {
        this.editDetailItem = item
        this.editDetailIndex = index
        this.editInputContent = item.file.name
        var self = this
        setTimeout(() => {
          self.$refs.editInput[0].focus()
        }, 100)
      }else if (type == 'delete') {
        this.$confirm('您确定要删除此附件吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.empMaterial = {
              fileId: null,
              fileName: null,
              subType: null,
            }
            this.detailList.splice(index, 1)
          })
          .catch(() => {})
      }
    },
    /** 编辑输入完成 */
    editInputBlur() {
      adminFileRenameFileAPI({
        fileId: this.editDetailItem.fileId,
        name: this.editInputContent
      })
        .then(res => {
          this.editDetailIndex = -1
          this.editDetailItem.file.name = this.editInputContent
          this.empMaterial.fileName = this.editInputContent
          this.editInputContent = ''
          this.editDetailItem = {}
          this.$message.success('编辑成功')
        })
        .catch(() => {
        })
    },
    // 预览图片
    previewFile(item, index) {
      var previewList = this.detailList.map(element => {
        return element.file
      })
      this.$wkPreviewFile.preview({
        index: index,
        data: previewList
      })
    },
    getFileTypeIcon(url) {
      const temps = url ? url.split('.') : []
      var ext = ''
      if (temps.length > 0) {
        ext = temps[temps.length - 1]
      } else {
        ext = ''
      }
      return getFileIconWithSuffix(ext)
    },
    isShowImage(name) {
      const temps = name ? name.split('.') : []
      var ext = ''
      if (temps.length > 0) {
        ext = temps[temps.length - 1]
      } else {
        ext = ''
      }
      return ['jpg', 'png', 'gif', 'jpeg'].includes(ext.toLowerCase())
    },
    /** 附件上传 */
    fileUpload(val) {
      // val.file
      this.$wkUploadFile.upload({
        request: adminFileUploadAPI,
        file: val.file
      }).then(completeData => {
        this.materialLoading = true
        this.empMaterial.fileId = completeData.res.data.fileId
        adminFileQueryByIdAPI(completeData.res.data.fileId).then(res => {
          this.empMaterial.fileName = res.data.name;
          this.detailList = [];
          this.detailList.push({file: res.data, fileId: completeData.res.data.fileId});
          this.materialLoading = false;
        }).catch(() => {
          this.materialLoading = false;
        })
      }).catch(() => {})
    },
    materialSubmit(){
      if (this.detailList.length <= 0) {
        this.$message.error('请上传材料')
        return
      }
      if (!this.empMaterial.subType && this.empMaterial.subType != '') {
        this.$message.error('请选择材料类型')
        return
      }
      if (!this.empMaterial.fileId){
        this.$message.error('请上传材料')
        return
      }
      this.materialOpen = false
      this.materialList.push(this.empMaterial);
    },
    addMaterialClick(){
      this.materialOpen = true
      this.empMaterial = {
        fileId: null,
        fileName: null,
        subType: null,
      }
      this.detailList = [];
    },
    deleteMaterialClick(){
      this.materialList = this.materialList.filter(item => {
        return !this.ids.includes(item.fileId)
      })
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.multiple = !selection.length
    },

    /**
     * 取消选择
     */
    handleCancel() {
      this.$emit('update:visible', false)
    },

    /**
     * 点击确定
     */
    handleConfirm() {
      this.$refs.formAddForm.$children[0].validate(valid => {
        if (valid) {
          if (this.title === '办理离职' || this.title === '人员调动' || this.title === '职位层级调整') {
            this.editForm.materialList = this.materialList;
          }
          this.$emit('update:form', this.editForm)
          this.$emit('pass')
        }
      })
    },

    /**
     * change 事件
     */
    wkFormChange(item, index, value, valueList) {
      this.$emit('change', item, index, value, valueList, this.editForm)
    },

    /**
     * 选择省市
     */
    selectProvince(data, item) {
      this.editForm[item.field].province = data.value
    },

    selectCity(data, item) {
      this.editForm[item.field].city = data.value
    }
  }
}
</script>
<style lang="scss" scoped>
.form-add-dialog-body {
  max-height: 55vh;
  overflow-x: hidden;
  overflow-y: auto;
}
/** 详情cell */
.detail-cell {
  position: relative;
  padding-right: 40px;
  padding-bottom: 20px;

  /** 详情 */
  .cell-upload-box {
    padding: 5px;
    border: 1px solid $--border-color-base;
    border-radius: 2px;

    .upload-icon {
      display: inline-block;
      margin-top: 25px;
      font-size: 40px;
      color: #777;
    }

    .upload-name {
      margin-top: 5px;
      color: #777;
    }
  }

  .detail-cell-box {
    padding: 5px;
    border: 1px solid $--border-color-base;
    border-radius: 2px;

    .detail-cell-body {
      position: relative;
      overflow: hidden;
      border-radius: 2px;

      span {
        display: block;
        width: 100%;
        text-align: center;

        img {
          width: auto;
          height: 100px;
          min-height: 100px;
          overflow: hidden;
          border-style: none;
        }
      }

      .body-handle {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 2;
        display: none;
        background-color: rgba(0, 0, 0, 0.5);

        .handle-items {
          margin-top: 35px;
          text-align: center;

          .handle-item {
            display: inline-block;
            width: 30px;
            height: 30px;
            line-height: 30px;
            cursor: pointer;
            background-color: rgba(0, 0, 0, 0.5);
            border-radius: 15px;

            i {
              color: white;
            }
          }
        }
      }
    }

    .detail-cell-body:hover {
      .body-handle {
        display: block;
      }
    }

    .detail-cell-footer {
      padding-top: 5px;

      .footer-name {
        display: flex;
        flex: 1;
        width: 180px;
        height: 40px;
        margin-right: 5px;
        overflow: hidden;
        color: $--color-text-primary;
        text-overflow: ellipsis;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
      }

      .el-input {
        ::v-deep input {
          height: 24px;
          line-height: 24px;
        }
      }

      .footer-item {
        flex-shrink: 0;
        padding: 3px;
        color: #777;
        cursor: pointer;

        &:hover {
          color: $--color-primary;
        }
      }
    }
  }
}

/** 拖拽上传 */
.cell-upload-box ::v-deep .el-upload {
  display: block;
}

.cell-upload-box ::v-deep .el-upload-dragger:hover {
  border-color: $--color-primary;
}

.cell-upload-box ::v-deep .el-upload-dragger {
  width: 100%;
  height: 131px;
  border-radius: 2px;
}
</style>
